{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "title: '`@value`'\n",
    "description: Generates boilerplate lifecycle methods for a struct.\n",
    "css: /static/styles/page-navigation.css\n",
    "website:\n",
    "  open-graph:\n",
    "    image: /static/images/mojo-social-card.png\n",
    "  twitter-card:\n",
    "    image: /static/images/mojo-social-card.png\n",
    "---"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can add the `@value` decorator on a struct to generate boilerplate\n",
    "lifecycle methods, including the member-wise `__init__()` constructor,\n",
    "`__copyinit__()` copy constructor, and `__moveinit__()` move constructor.\n",
    "\n",
    "For example, consider a simple struct like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "@value\n",
    "struct MyPet:\n",
    "    var name: String\n",
    "    var age: Int"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mojo sees the `@value` decorator and notices that you don't have any constructors\n",
    "and it synthesizes them for you, the result being as if you had actually\n",
    "written this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "struct MyPet:\n",
    "    var name: String\n",
    "    var age: Int\n",
    "\n",
    "    fn __init__(inout self, owned name: String, age: Int):\n",
    "        self.name = name^\n",
    "        self.age = age\n",
    "\n",
    "    fn __copyinit__(inout self, existing: Self):\n",
    "        self.name = existing.name\n",
    "        self.age = existing.age\n",
    "\n",
    "    fn __moveinit__(inout self, owned existing: Self):\n",
    "        self.name = existing.name^\n",
    "        self.age = existing.age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mojo synthesizes each lifecycle method only when it doesn't exist, so\n",
    "you can use `@value` and still define your own versions to override the default\n",
    "behavior. For example, it is fairly common to use the default member-wise and\n",
    "move constructor, but create a custom copy constructor."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For more information about these lifecycle methods, read\n",
    "[Life of a value](/mojo/manual/lifecycle/life.html)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Mojo",
   "language": "mojo",
   "name": "mojo-jupyter-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "mojo"
   },
   "file_extension": ".mojo",
   "mimetype": "text/x-mojo",
   "name": "mojo"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
